<?php
namespace Home\Controller;
use Lib;
class FriendController extends Lib\Controller {
	function __construct() {
		parent::__construct ();
	}
	/**
	 * 添加好友
	 * argv name
	 */
	public function friendAdd(){
		//参数检查
		if(empty($this->userInfo['user_id']) || empty($this->param['friend_id'])){
			$this->error(ERROR_NO_ARGV,'参数错误');
		}
		//检测好友是否存在		
		$u = $this->u->where(array('user_id'=>$this->param['friend_id']))->select();
		if(empty($u)){
			$this->error(ERROR_NO_USER,'好友不存在');
		}else{
			//使用事务处理，添加好友必须通知好友有人添加他
			$this->u->startTrans();
			$f = D('Friends');
			$fr = $f->addFriend($this->userInfo['user_id'],$this->param['friend_id']);

			//添加成功，通知好友已经添加了
			$m = D('Message');
			$mr = $m->send($this->userInfo['user_id'],$this->param['friend_id'],$message='',$type='');
			if(empty($fr) || empty($mr)){
				//操作回滚
				$this->u->rollback();
				$this->error(ERROR_SQL_FAILING,'操作失败，请重试');
			}else{
				//提交操作				
				$this->u->commit();
				$this->show('操作成功');
			}
		}
	}
	/**
	 * 删除好友
	 */
	public function friendDelete(){
		if(empty($this->param['friend_id'])){
			$this->error(ERROR_NO_ARGV,'参数错误，请检查');
		}		
		$f = D('Friends');
		$fr = $f->where(array('user_id'=>$this->userInfo['user_id'],'friend_id'=>$this->param['friend_id']))->delete();
		if(empty($fr)){
			$this->show('操作成功');
		}else{
			$this->error(ERROR_SQL_FAILING,'数据库操作错误　' . $f->getError());
		}
	}
	/**
	 * 获取好友列表
	 */
	public function getFriendList(){
		$f = D('Friends');
		$fr = $f->where(array('user_id'=>$this->userInfo['user_id']))->find();
		if(empty($fr)){
			$this->show($fr);
		}else{
			$this->error(ERROR_SQL_FAILING,'数据库操作错误　' . $f->getError());
		}
	}
}	
?>